/*
 * @Description: 
 * @Author: zheng yiliang
 * @Date: 2021-03-17 20:15:59
 * @LastEditTime: 2021-05-29 21:32:24
 * @LastEditors: zheng yiliang
 */
var express = require('express');
var router = express.Router();
const bcrypt = require('bcryptjs')
const { Users, Roles } = require('../model')
const { SuccessModel, ErrorModel } = require('../util')
const { decrypted } = require('../util/encrypt') // 密码解密
const { setToken } = require('../util/jwt')
const loginCheck = require('../middleware/loginCheck')
const { USER_PASSWORD, USER_ROUSER__ID, PUBLIC_ERROR_MSG } = require('../core/constant');
const mongoose = require('../core/mongodb')
const { Types } = mongoose

router.post('/login', async (req, res) => {
  const { username, password } = req.body
  const user = await Users.findOne({ 'del_flag': 0, $or: [{ 'user_name': username }, { 'user_email': username }, { 'user_telephone_number': username }] })
  if (user) {
    if (!user.user_status) return res.json(new ErrorModel('该用户已被禁用，请联系管理员'))
    const pwd = decrypted(password) // 密码解密
    const isValid = await bcrypt.compare(pwd, user.user_password) // 解密后的密码和数据库里对比
    if (isValid) {
      const token = setToken({ _id: user._id })
      res.cookie("openid", user.qq_id, { maxAge: 86400000, httpOnly: true });
      return res.json(new SuccessModel({ token }, '登录成功'))
    }
  }
  return res.json(new ErrorModel('用户名或密码错误'))
})


router.post('/logout', (req, res) => {
  // cleanToken(res)
  res.clearCookie('openid')
  return res.json(new SuccessModel('退出成功'))
})


// 获取用户列表
router.get('/list', loginCheck, (req, res) => {
  // // 日期范围
  // dateRange: []
  const { pagenum, pagesize, userName, phonenumber, status, dateRange } = req.query
  const params = { 'del_flag': 0 }
  if (userName) params.user_name = { $regex: eval(`/${userName}/ig`) }
  if (phonenumber) params.user_telephone_number = { $regex: eval(`/${phonenumber}/ig`) }
  if (status) params.user_status = status
  if (dateRange) params.create_time = {
    "$gte": new Date(`${dateRange[0]} 00:00:00`),
    "$lte": new Date(`${dateRange[1]} 23:59:59`)
  }
  Users.countDocuments(params, (error, count) => {
    if (error) {
      // logger.error(`user::/list::error:${JSON.stringify(error)}`);
      return res.json(new ErrorModel(error));
    } else {
      Users.find(params, { user_password: 0 }).populate('roles', { _id: 1, role_key: 1, role_name: 1 }).skip((pagenum - 1) * pagesize).limit(parseInt(pagesize) || 5).sort({ 'create_time': 1 }).exec((err, doc) => {
        if (err) {
          return res.json(new ErrorModel(err));
        } else {
          // const copyDoc = JSON.parse(JSON.stringify(doc))
          const users = doc.map(item => {
            return {
              username: item.user_name,
              // email: item.user_email,  
              // avatar: item.user_avatar,
              mobile: item.user_telephone_number,
              roleName: item.roles.role_name,
              status: item.user_status,
              // roleKey: item.roles.role_key,
              nickName: item.nick_name,
              // roleId: item.roles._id,
              createTime: item.create_time,
              userId: item._id,
              isHidden: item.is_developer
            }
          })
          return res.json(new SuccessModel({
            users,
            total: count,
          }, '用户列表获取成功'));
        }
      })
    }
  })
})


// 可被禁用账号
// const deveAccTel = ['14759491315']

// // 改变用户状态，false为不可登录
router.put('/setState', loginCheck, async (req, res) => {
  const { id, status } = req.body
  // 开发者账号不能被停用
  const users = await Users.findOne({ '_id': id }, { is_developer: 1, user_name: 1 })
  if (!users.is_developer) {
    return res.json(new ErrorModel('开发者账号不能被停用'))
  }
  // 根据 id 更新状态
  const result = await Users.findByIdAndUpdate(id, {
    user_status: status
  })
  // if (result.ok) {
  return res.json(new SuccessModel(`${users.user_name}已${status ? '启用' : '禁用'}`))
  // }
  // return res.json(new ErrorModel('用户状态设置失败'))
})

// 获取用户详情
router.get('/detail', loginCheck, async (req, res) => {
  const { id } = req.query
  const users = await Users.findUserById(id)
  return res.json(new SuccessModel(users, '用户详情获取成功'))
})

// 修改用户
router.put('/edit', loginCheck, async (req, res) => {
  const { email, id, mobile, status, username, nickname } = req.body
  // 开发者账号不能被停用
  const users = await Users.findOne({ '_id': id }, { is_developer: 1, user_name: 1 })
  if (!users.is_developer && !status) {
    return res.json(new ErrorModel('开发者账号不能被停用'))
  }
  Users.findByIdAndUpdate(id, {
    user_email: email,
    user_telephone_number: mobile,
    user_status: status,
    user_name: username,
    nick_name: nickname
  }, (err, doc) => {
    if (err) {
      const { keyValue } = err
      if (keyValue.user_email) {
        return res.json(new ErrorModel('邮箱已存在'))
      }
      if (keyValue.user_telephone_number) {
        return res.json(new ErrorModel('手机号已存在'))
      }
      if (keyValue.user_name) {
        return res.json(new ErrorModel('用户名已存在'))
      }
      return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
    }
    return res.json(new SuccessModel('修改成功'))
  })

})

// 获取用户详情
router.delete('/delete', loginCheck, async (req, res) => {
  const { id } = req.body
  const result = await Users.findByIdAndUpdate(id, {
    del_flag: 1
  })
  return res.json(new SuccessModel('用户已删除'))
})

// 新增用户
router.post('/add', loginCheck, async (req, res) => {
  const { username, email, mobile, nickname, roles, status } = req.body
  // const { _id } = await Roles.findOne({ 'role_key': 'visitor' }, { _id: 1 })
  const salt = await bcrypt.genSalt(10)
  const user_password = await bcrypt.hash(USER_PASSWORD, salt)
  const user = new Users({
    user_name: username,
    user_email: email,
    user_telephone_number: mobile,
    nick_name: nickname,
    user_password,
    roles: Types.ObjectId(roles),
    user_status: status
  });
  /*实例.save((err,docs)=>{回调函数}) 来将数据保存到数据库*/
  user.save((err, docs) => {
    if (err) {
      const { keyValue } = err
      if (keyValue.user_email) {
        return res.json(new ErrorModel('邮箱已存在'))
      }
      if (keyValue.user_telephone_number) {
        return res.json(new ErrorModel('手机号已存在'))
      }
      if (keyValue.user_name) {
        return res.json(new ErrorModel('用户名已存在'))
      }
      return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
    }
    return res.json(new SuccessModel('用户添加成功'))
  });

})

router.put('/roleUpdate', loginCheck, async (req, res) => {
  const { userId, roleId } = req.body
  const result = await Users.findByIdAndUpdate(userId, {
    roles: roleId
  })
  return res.json(new SuccessModel('角色更新成功'))
})
module.exports = router;
